package com.example.fourm.controller;

import com.example.fourm.common.AppResult;
import com.example.fourm.common.ResultCode;
import com.example.fourm.config.AppConfig;
import com.example.fourm.exception.ApplicationException;
import com.example.fourm.model.User;
import com.example.fourm.services.IUserService;
import com.example.fourm.utils.MD5Util;
import com.example.fourm.utils.StringUtil;
import com.example.fourm.utils.UUIDUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.net.http.HttpRequest;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private IUserService userService;
    @RequestMapping("/register")
    public AppResult register(@RequestParam("username")@NonNull String username,
                              @RequestParam("nickname")@NonNull String nickname,
                              @RequestParam("password")@NonNull String password,
                               @NonNull String passwordRepeat  ) {
        if(!password.equals(passwordRepeat)) {
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.getMessage());
            return AppResult.failure(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
       User user = new User();
        user.setUsername(username);
        user.setNickname(nickname);
        String salt = UUIDUtil.UUID_32();
        String encryPassword = MD5Util.md5(password, salt);
        user.setPassword(encryPassword);
        user.setSalt(salt);
        userService.createNormalUser(user);
        return AppResult.success();
    }

    @PostMapping("/login")
    public AppResult login(@RequestParam("username") @NonNull String username,
                           @RequestParam("password") @NonNull String password, HttpServletRequest request) {
        User user = userService.selectByUserName(username, password);
        HttpSession session = request.getSession(true); //session为空则创建session
        session.setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success("登录成功");
    }

    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,
                                       @RequestParam(value = "id",required = false) Long id) {
        User user = null;
        if(id == null) {
            HttpSession session = request.getSession(false);
            //判断session是否为空
            user = (User) session.getAttribute(AppConfig.USER_SESSION);
        }else {
            user = userService.selectByPrimaryKey(id);
            if (user == null) {
                return AppResult.failure(ResultCode.FAILED_USER_NOT_EXISTS);
            }
        }
        return AppResult.success(user);
    }

    @PostMapping("/logout")
    public AppResult logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if(session != null) {
            log.info("登录状态进行注销");
            session.invalidate();
        }
        return AppResult.success("注销成功");
    }
    @PostMapping("modifyInfo")
    public AppResult modifyInfo(@RequestParam(value = "username",required = false) String username,
                                @RequestParam(value = "nickname",required = false) String nickname,
                                @RequestParam(value = "gender",required = false) Byte gender,
                                @RequestParam(value = "email",required = false) String email,
                                @RequestParam(value = "phoneNum",required = false) String phoneNum,
                                @RequestParam(value = "remark",required = false) String remark,HttpServletRequest request){
        if (StringUtil.isEmpty(username) && StringUtil.isEmpty(nickname)
                && StringUtil.isEmpty(email) && StringUtil.isEmpty(phoneNum)
                && StringUtil.isEmpty(remark) && gender == null) {
            // 返回错误信息
            return AppResult.failure("请输入要修改的内容");
        }
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setUsername(username);
        newUser.setNickname(nickname);
        newUser.setGender(gender);
        newUser.setEmail(email);
        newUser.setPhoneNum(phoneNum);
        newUser.setRemark(remark);
        userService.modifyInfo(newUser);
        user = userService.selectByPrimaryKey(user.getId());
        session.setAttribute(AppConfig.USER_SESSION, user);
        return AppResult.success(user);
    }

    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                   @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @RequestParam("newPassword") @NonNull String newPassword,
                                    @RequestParam("passwordRepeat") @NonNull String passwordRepeat) {
        //校验新密码与确认密码是否相同
        if(!passwordRepeat.equals(newPassword)) {
            log.warn("两个密码不一致");
            return AppResult.failure("两个密码不一致");
        }
        HttpSession session = request.getSession(false);
        User user = (User)session.getAttribute(AppConfig.USER_SESSION);
        userService.modifyPassword(user.getId(), oldPassword, newPassword);
        if(session != null) {
            session.invalidate();
        }
        return AppResult.success("更新密码成功");
    }
}
